<script setup lang="ts">
import { h, ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { NModal, NCard, NForm, NSpace, NFormItem, NInput, NSelect, NButton, NDataTable, NPagination, NPopconfirm, useNotification } from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { useDictStore } from '@/stores/dictStore'
import { useUserStore } from '@/stores/userStore'
import http from '@/tools/http'

const userStore = useUserStore()

type RowData = {
    datasourceName?: string
    dbType?: string
    jdbcUrl?: string
    username?: string
    password?: string
}

const datasourceTableColumns = [
    {
        title: "数据源名称",
        key: "datasourceName",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "数据库类型",
        key: "dbType",
        width: 60,
        render(rowData: RowData, rowIndex: number) {
            return dictStore.dictItem("DB_TYPE", rowData.dbType)
        }
    }, {
        title: "jdbc-url",
        key: "jdbcUrl",
        width: 250,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "账号",
        key: "username",
        width: 60,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "密码",
        key: "password",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "操作",
        key: "actions",
        width: "192px",
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    userStore.hasAuth("code-generator-tables") ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => showTables(rowData)
                        },
                        { default: () => "查看" }
                    ) : null,
                    userStore.hasAuth("code-generator:edit") ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openEditDatasource(rowData)
                        },
                        { default: () => "编辑" }
                    ) : null,
                    userStore.hasAuth("code-generator:delete") ? h(
                        NPopconfirm,
                        {
                            onPositiveClick: (e: MouseEvent) => deleteDatasource()
                        },
                        {
                            trigger: () => {
                                return h(
                                    NButton,
                                    {
                                        size: "small",
                                        onclick: () => openDeleteDatasource(rowData)
                                    },
                                    { default: () => "删除" }
                                )
                            },
                            default: () => { return "确认删除该数据源？" }
                        }
                    ) : null
                ]
            )
        }
    }
]

const datasourceData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const datasourceSearchFormValue = reactive({
    pageNum: 1,
    pageSize: 10,
    datasourceName: "",
    dbType: null
})

const dictStore = useDictStore()
const router = useRouter()

onMounted(() => {
    pageDatasource()
})

const visiable = ref<boolean>(false)
const title = ref<string>("")
const formRef = ref<FormInst | null>(null)
const formData = reactive<RowData>({
    datasourceName: "",
    dbType: "0",
    jdbcUrl: "",
    username: "",
    password: ""
})

const formRules = {
    datasourceName: {
        required: true,
        message: '请输入数据源名称',
        trigger: ['input']
    },
    dbType: {
        required: true,
        message: '请选择数据库类型',
        trigger: ['input']
    },
    jdbcUrl: {
        required: true,
        message: '请输入jdbc-url',
        trigger: ['input']
    },
    username: {
        required: true,
        message: '请输入账号',
        trigger: ['input']
    },
    password: {
        required: true,
        message: '请输入密码',
        trigger: ['input']
    }
}

function pageNumChange(pageNum: number) {
    datasourceSearchFormValue.pageNum = pageNum
    pageDatasource()
}

function pageSizeChange(pageSize: number) {
    datasourceSearchFormValue.pageSize = pageSize
    pageDatasource()
}

function showTables(rowData: RowData) {
    router.push({
        name: 'code-generator-tables',
        query: { datasourceName: rowData.datasourceName }
    })
}

function openAddDatasource() {
    visiable.value = true
    title.value = "添加数据源"
    formData.datasourceName = ""
    formData.dbType = "0"
    formData.jdbcUrl = ""
    formData.username = ""
    formData.password = ""
}

function openEditDatasource(row: any) {
    visiable.value = true
    title.value = "编辑数据源"
    formData.datasourceName = row.datasourceName
    formData.dbType = row.dbType
    formData.jdbcUrl = row.jdbcUrl
    formData.username = row.username
    formData.password = row.password
}

function openDeleteDatasource(row: any) {
    formData.datasourceName = row.datasourceName
    formData.dbType = row.dbType
    formData.jdbcUrl = row.jdbcUrl
    formData.username = row.username
    formData.password = row.password
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (title.value === "添加数据源") {
                addDatasource()
            } else {
                updateDatasource()
            }
            visiable.value = false
        }
    })
}

function pageDatasource() {
    http.post("/datasource/page", datasourceSearchFormValue).then(({ data }) => {
        datasourceData.pageNum = data.data.pageNum
        datasourceData.pageSize = data.data.pageSize
        datasourceData.pages = data.data.pages
        datasourceData.total = data.data.total
        datasourceData.list.length = 0
        for (let i = 0; i < data.data.list.length; i++) {
            datasourceData.list.push(data.data.list[i])
        }
    })
}

const notification = useNotification()

function testConnection() {
    http.post("/datasource/test", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '链接成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
        }
    })
}

function addDatasource() {
    http.post("/datasource/add", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '添加成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageDatasource()
        }
    })
}

function updateDatasource() {
    http.post("/datasource/update", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '修改成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageDatasource()
        }
    })
}

function deleteDatasource() {
    http.post("/datasource/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageDatasource()
        }
    })
}
</script>

<template>
    <div id="flame-container">
        <div class="search">
            <n-form :model="datasourceSearchFormValue" inline label-placement="left">
                <n-form-item label="数据源名称" path="datasourceName">
                    <n-input v-model:value="datasourceSearchFormValue.datasourceName" placeholder="请输入数据源名称" clearable />
                </n-form-item>
                <n-form-item>
                    <n-select style="width:196px" v-model:value="datasourceSearchFormValue.dbType"
                        :options="dictStore.dict('DB_TYPE')" placeholder="请选择数据库类型" clearable />
                </n-form-item>
                <n-form-item>
                    <n-button v-if="userStore.hasAuth('code-generator:add')" attr-type="button"
                        @click="pageDatasource()">查询</n-button>
                </n-form-item>
            </n-form>
        </div>
        <div class="btn-group">
            <n-button attr-type="button" @click="openAddDatasource()">新增</n-button>
        </div>
        <div class="data-table">
            <n-data-table :scroll-x="762" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :columns="datasourceTableColumns" :data="datasourceData.list" :bordered="false" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" :item-count="datasourceData.total" :page-sizes="[5, 10, 30, 50, 100]"
                :on-update-page="pageNumChange" :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
        </div>
    </div>
    <n-modal v-model:show="visiable">
        <n-card style="width: 500px" :title="title">
            <n-form ref="formRef" :model="formData" :rules="formRules" label-width="92px" label-placement="left"
                require-mark-placement="left">
                <n-form-item label="数据源名称" path="datasourceName">
                    <n-input v-model:value="formData.datasourceName" :disabled="title === '编辑数据源'" placeholder="请输入数据源名称" />
                </n-form-item>
                <n-form-item label="数据库类型" path="dbType">
                    <n-select v-model:value="formData.dbType" :options="dictStore.dict('DB_TYPE')" placeholder="请选择数据库类型"
                        clearable />
                </n-form-item>
                <n-form-item label="jdbc-url" path="jdbcUrl">
                    <n-input v-model:value="formData.jdbcUrl" placeholder="请输入jdbc-url" />
                </n-form-item>
                <n-form-item label="账号" path="username">
                    <n-input v-model:value="formData.username" placeholder="请输入账号" />
                </n-form-item>
                <n-form-item label="密码" path="password">
                    <n-input v-model:value="formData.password" placeholder="请输入密码" />
                </n-form-item>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button attr-type="button" @click="visiable = false">取消</n-button>
                    <n-button attr-type="button" @click="testConnection()">测试链接</n-button>
                    <n-button attr-type="button" @click="submit()">提交</n-button>
                </n-space>
            </template>
        </n-card>
    </n-modal>
</template>

<style scoped>
</style>